package cn.edu.pzhu.javaweb.util;
import java.awt.image.BufferedImage;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Color;
import java.util.Random;

public class RandomCharImageGenerator {
    // 私有成员：包含图像和图像上的文本
    private BufferedImage image;
    private String text;
    // 字符源：数字和字母的组合
    private final String CHAR_POOL = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private Random random = new Random();

    // 向外部模块提供的get方法
    public BufferedImage getImage() {
        return image;
    }

    public String getText() {
        return text;
    }

    // 生成图像的初始化方法，参数为图像宽、高、绘制字符数量n
    public void initialize(int width, int height, int n) {
        // 创建BufferedImage对象
        image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();

        // 绘制背景
        g.setColor(getRandomColor(200, 250));
        g.fillRect(0, 0, width, height);

        // 设置字体
        g.setFont(new Font("Arial", Font.BOLD, height - 5));

        // 生成并绘制n个字符组成的字符串
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < n; i++) {
            char c = CHAR_POOL.charAt(random.nextInt(CHAR_POOL.length()));
            sb.append(c);
            // 绘制字符，设置随机颜色和位置
            g.setColor(getRandomColor(0, 160));
            g.drawString(String.valueOf(c), (width / n) * i + 5, height - random.nextInt(5));
        }
        text = sb.toString();

        // 绘制干扰线（可选，增强图像复杂度）
        for (int i = 0; i < 5; i++) {
            g.setColor(getRandomColor(160, 200));
            int x1 = random.nextInt(width);
            int y1 = random.nextInt(height);
            int x2 = random.nextInt(width);
            int y2 = random.nextInt(height);
            g.drawLine(x1, y1, x2, y2);
        }

        g.dispose();
    }

    // 生成随机颜色的工具方法
    private Color getRandomColor(int min, int max) {
        int r = min + random.nextInt(max - min);
        int g = min + random.nextInt(max - min);
        int b = min + random.nextInt(max - min);
        return new Color(r, g, b);
    }
}
